package org.spbsu.apco.server.system;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spbsu.apco.common.monitoring.event.ServiceEvent;
import org.spbsu.apco.server.monitoring.event.MonitorService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Queue;

/**
 * User: mikpan
 * Date: 12/12/12
 * Time: 3:51 PM
 */
@Service(value = "SystemInfoSync")
public class SystemInfoSync {
    private static final Logger log = LoggerFactory.getLogger(SystemInfoSync.class);

    @Resource
    MonitorService monitorService;

    @Resource
    SystemService systemService;

    public SystemInfoSync() {
        log.info("Daemon initialized.");
    }

    @Scheduled(fixedDelay = 3000)  //TODO: properties value to be used
    public void run() {
        Queue<ServiceEvent> events = monitorService.getEvents();
        log.trace("Checking {} events.", events.size());
        for (ServiceEvent e : events) {
            final String clientId = e.getOriginatorId();
            final String macAddress = e.getMacAddress();
            Runner runner = systemService.getRunnerById(clientId);
            Node node = systemService.getNodeByMac(macAddress);
            if (runner == null) {
                runner = systemService.registerRunner(clientId);
                log.info("Added runner {}", runner);
            }
            if (node == null) {
                node = systemService.registerNode(macAddress);
                log.info("Added node {}", node);
            }
            node.addRunner(runner);
        }
    }
}
